package org.study.event.core.transaction.manager;

import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.study.event.core.common.EventMessage;
import org.study.event.core.transaction.AbstractTranactionListenerManager;

/***
 * 不使用监听的操作
 * 
 * @author 陈波
 *
 */
public class TransactionalSyncRegisterManager extends AbstractTranactionListenerManager {

	/***
	 * 于线程上下文相关的数据
	 */
	private static ThreadLocal<EventMessage> threadLocalMessage = new ThreadLocal<>();

	/***
	 * 提交完成操作
	 */
	private final TransactionSynchronization transactionSynchronization = new TransactionCommitSynchronization();

	@Override
	public void pushTransactionEvent(EventMessage message) {
		try {
			if (threadLocalMessage.get() != null) {
				threadLocalMessage.remove();
			}
			threadLocalMessage.set(message);
			TransactionSynchronizationManager.registerSynchronization(transactionSynchronization);
		} catch (Throwable e) {
			threadLocalMessage.remove();
		}
	}

	/***
	 * 提交完成
	 * 
	 * @author 陈波
	 *
	 */
	class TransactionCommitSynchronization extends TransactionSynchronizationAdapter {
		@Override
		public void afterCommit() {
			try {
				EventMessage eventMessage = threadLocalMessage.get();
				if (eventMessage != null) {
					TransactionalSyncRegisterManager.this.afterCommit(eventMessage);
				}
			} catch (Throwable e) {
				threadLocalMessage.remove();
			}
		}

		@Override
		public void beforeCommit(boolean readOnly) {
			try {
				EventMessage eventMessage = threadLocalMessage.get();
				if (eventMessage != null) {
					TransactionalSyncRegisterManager.this.beforeCommit(eventMessage);
				}
			} catch (Throwable e) {
				threadLocalMessage.remove();
			}
		}

		/***
		 * 完成事件
		 */
		@Override
		public void afterCompletion(int status) {
			try {
				EventMessage eventMessage = threadLocalMessage.get();
				if (eventMessage != null) {
					/**
					 * 回滚完成
					 */
					if (status == TransactionSynchronization.STATUS_COMMITTED) {
						TransactionalSyncRegisterManager.this.afterRollBack(eventMessage);
					} else {
						TransactionalSyncRegisterManager.this.afterCommpetion(eventMessage);
					}
				}
			} finally {
				// 最后所有完毕的时候清除数据
				threadLocalMessage.remove();
			}

		}

	}

}
